import { WorkflowContext } from "@/context/WorkflowContext";
import { nodeTemplate2FlowNode } from "@/function/utils";
import {
  Avatar,
  Box,
  Button,
  Drawer,
  DrawerBody,
  DrawerCloseButton,
  DrawerContent,
  DrawerFooter,
  DrawerHeader,
  DrawerOverlay,
  Flex,
} from "@chakra-ui/react";
import { useViewport } from "reactflow";
import React, { useCallback, useContext, useMemo, useState } from "react";
import { moduleTemplatesFlat } from "./template/constants";

const sliderWidth = 390;

const NodeTemplatesModal = ({ isOpen, onClose }: any) => {
  console.log(isOpen);
  const { basicNodeTemplates, setNodes } = useContext(WorkflowContext);

  const { reactFlowWrapper } = useContext(WorkflowContext);
  console.log(reactFlowWrapper, "reactFlowWrapper");

  const { x, y, zoom } = useViewport();
  const onAddNode = useCallback(
    async ({ template, position }: any) => {
      // const templateNode = await (async ()=>{
      // })
      // base node
      const baseTemplate = moduleTemplatesFlat.find(
        (item) => item.id === template.id
      );
      console.log(baseTemplate);
      if (!reactFlowWrapper?.current) return;
      // setNodes(nodeTemplate2FlowNode({
      //     ...template
      // }))

      const reactFlowBounds = reactFlowWrapper.current.getBoundingClientRect();
      console.log(reactFlowBounds, "reactFlowBounds");
      // const reactFlowBounds = reactFlowWrapper.current.getBoundingClientRect();
      console.log("position:x", position.x, reactFlowBounds.left, x, zoom);
      console.log("position:y", position.y, reactFlowBounds.top, y, zoom);
      const mouseX = (position.x - reactFlowBounds.left - x) / zoom;
      const mouseY = (position.y - reactFlowBounds.top - y) / zoom;

      // const mouseX = 100;
      // const mouseY = 100;
      console.log(mouseX, mouseY, "mouseY");

      const node = nodeTemplate2FlowNode({
        template: {
          ...baseTemplate,
        },
        position: { x: mouseX, y: mouseY - 20 },
        selected: true,
      });

      setNodes((state) =>
        state
          .map((node) => ({
            ...node,
            selected: false,
          }))
          // @ts-ignore
          .concat(node)
      );
    },
    [x, y, zoom]
  );

  const formatTemplates = useMemo(() => {
    return basicNodeTemplates;
  }, []);
  
  const [dragPosition, setDragPosition] = useState({ x: 0, y: 0 });

  console.log("basicNodeTemplates", basicNodeTemplates, formatTemplates);
  return (
    <>
      <Box
        zIndex={2}
        display={isOpen ? "block" : "none"}
        position={"absolute"}
        top={0}
        left={0}
        bottom={0}
        w={`${sliderWidth}px`}
        maxW={"100%"}
        // onClick={onClose}
        fontSize={"sm"}
      >
        {/* <RenderList/> */}
        <Box
          display={"flex"}
          zIndex={3}
          flexDirection={"column"}
          position={"absolute"}
          top={"10px"}
          pl={"20px"}
          pr={"20px"}
          w={`${sliderWidth}px`}
          left={0}
          pt={"20px"}
          pb={4}
          bg={"white"}
          boxShadow={"3px 0 20px rgba(0,0,0,0.2)"}
          borderRadius={"0 20px 20px 0"}
          transition={".2s ease"}
        >
          {/* Header */}
          <Box onClick={onClose}></Box>
          <Box>
            {formatTemplates.map((template:any,key:any) => (
              <Flex
                key={key}
                draggable="true"
                onDragStart={(e) => {
                    const { left, top } = e.currentTarget.getBoundingClientRect();
                    const { clientX, clientY } = e;
                    setDragPosition({ x: clientX - left, y: clientY - top });
                }}
                onDragEnd={(e) => {
                    const { clientX, clientY } = e;
                    const newX = clientX - dragPosition.x;
                    const newY = clientY - dragPosition.y;
                    if (newX < sliderWidth) return;
                    onAddNode({
                      template,
                      position: { x: newX, y: newY },
                    });
                }}
                onClick={(e) => {
                  e.stopPropagation();
                  return;
                }}
                p={5}
                className="items-center"
                _hover={{ bg: "myWhite.600" }}
              >
                <Avatar
                  src={template.avatar}
                  w={"24px"}
                  h={"24px"}
                  objectFit={"contain"}
                  borderRadius={"0"}
                />
                <Box ml={3}>{template.name}</Box>
              </Flex>
            ))}
          </Box>
        </Box>
      </Box>
    </>
  );
};

const RenderList = React.memo(function RenderList({}: any) {
  const { x, y, zoom } = useViewport();
  return <></>;
});

export default React.memo(NodeTemplatesModal);
